package app

import (
	"context"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"main/config"
	"main/internal/pkg/ks"
	"time"
)

var R *gin.Engine
var Db *gorm.DB
var Redis *redis.Client
var RedisCtx = context.Background()
var JWTSecretKey = []byte(config.Cfg.Jwt.Secret) // 用于签名的密钥

func init() {
	//    "appid": "ks654429322237522594",
	//    "appsecret": "ks654429322237522594"

	r := gin.Default()
	R = r
	//启动跨域
	corsConfig := cors.DefaultConfig()
	corsConfig.AllowOrigins = []string{"*"}
	corsConfig.AllowHeaders = []string{"*"}
	corsConfig.AllowCredentials = true
	R.Use(cors.New(corsConfig))

	//初始化GORM
	dsn := config.Cfg.Mysql.User + ":" + config.Cfg.Mysql.Pass + "@tcp(" + config.Cfg.Mysql.Addr + ")/" + config.Cfg.Mysql.Name + "?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}
	//开启调试
	Db = db
	Db = Db.Debug()
	//启动迁移表
	err = Db.AutoMigrate(
		&SysAdmin{},
		&SysGift{},
		&SysApiList{},
		&SysLiveMsg{},
		&SysUserList{},
		&SysUserLiveList{},
	)
	if err != nil {
		panic(err)
	}
	//启动redis
	redis := redis.NewClient(&redis.Options{
		Addr:     config.Cfg.Redis.Addr,
		Password: config.Cfg.Redis.Pass, // no password set
		DB:       0,                     // use default DB
	})
	Redis = redis

	//启动快手自动刷新AccToken
	go func() {
		for {
			ks.Acctoken, _ = ks.GetAccessToken(config.Cfg.Ksgame.Appid, config.Cfg.Ksgame.Appsecret)
			time.Sleep(time.Hour)
		}
	}()

}
